#include "connectionfactory.h"

using namespace swp;

ConnectionFactory* connectionFactory = 0;

ConnectionFactory* ConnectionFactory::getInstance()
{
    if (connectionFactory == 0)
    {
        connectionFactory = new ConnectionFactory();
    }

    return connectionFactory;
}

void ConnectionFactory::destroy()
{
    delete connectionFactory;
    connectionFactory = 0;
}

void ConnectionFactory::registerGraphicItemForConnection(
    unsigned int connectionId,
    AbstractLineGraphicItem* item)
{
    if (!m_registeredGraphicItems.contains(connectionId))
    {
        m_registeredGraphicItems[connectionId] =
            dynamic_cast<AbstractLineGraphicItem*>(item->copy());
    }
}

void ConnectionFactory::unregisterGraphicItemForConnection(
        unsigned int connectionId)
{
    if (m_registeredGraphicItems.contains(connectionId))
    {
        AbstractLineGraphicItem* item =
            m_registeredGraphicItems[connectionId];
        m_registeredGraphicItems.remove(connectionId);

        delete item;
    }
}

AbstractLineGraphicItem* ConnectionFactory::graphicItemForConnection(
    unsigned int connectionId) const
{
    AbstractLineGraphicItem* ret = 0;

    if (m_registeredGraphicItems.contains(connectionId))
    {
        ret = dynamic_cast<AbstractLineGraphicItem*>(
            m_registeredGraphicItems[connectionId]->copy());
    }

    return ret;
}

ConnectionFactory::ConnectionFactory() : m_registeredGraphicItems()
{

}

ConnectionFactory::~ConnectionFactory()
{
    foreach (AbstractLineGraphicItem* item, m_registeredGraphicItems)
    {
        delete item;
    }
}
